<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
* Initialize messages that will be shown to the user.
* @access private 
*/
function init_messages($content)
{
    $ci = &get_instance();
    
    $ci->messages['add_success']        = $content . ' Successfully Created';
    $ci->messages['edit_success']       = $content . ' Successfully Edited';
    $ci->messages['delete_success']     = $content . ' Successfully Deleted';
    $ci->messages['archived']           = $content . ' Archived';
    $ci->messages['add_failed']         = 'Please Fill-up All the Input Fields Needed';
    $ci->messages['edit_failed']        = 'Please Fill-up All the Input Fields Needed';
    $ci->messages['delete_failed']      = 'This ' .$content. ' Cannot be Deleted';
    $ci->messages['action_failed']      = 'No Items Selected';
    $ci->messages['active']             = $content. ' Activated';
    $ci->messages['inactive']           = $content. ' Deactivated';
    $ci->messages['accept']             = $content. ' Accepted';
    $ci->messages['decline']            = $content. ' Declined';
    $ci->messages['server_error']       = 'Request Failed';
}

/**
 * Retrieve specific message to be shown
 * @param type $message_type
 */
function get_message($message_type)
{
    $ci = &get_instance();
    $message = array();
    
    $message['message_type'] = $message_type;
    
    if ( isset($message_type) ) // check if a message type is passed.
    {
        if ( isset($ci->messages[$message_type]) ) // countercheck for specified messages.
        {
            if($message_type === 'add_success' OR $message_type === 'edit_success' OR $message_type === 'delete_success' OR $message_type === 'archived')
            {
                $message['class'] = 'alert alert-success';
            } 
            if($message_type === 'add_failed' OR $message_type === 'edit_failed' OR $message_type === 'delete_failed' OR $message_type === 'action_failed')
            {
                $message['class'] = 'alert alert-danger';
            }
            $message['title'] = ucwords( str_replace('_', ' ', $message_type) );
            $message['message'] = $ci->messages[$message_type];
            
        } else // if not on the list use the message itself.
        {
            $message['class'] = 'alert alert-info';
            $message['title'] = 'Failed';
            $message['message'] = $message_type;
        }
        return $message;
    } else
    {
        return NULL;
    }
}

/**
 * Function to clear breadcrumbs from session
 * @access public
 */
function clear_breadcrumbs()
{
    $ci = &get_instance();
    
    // clear session breadcrumbs
    $ci->session->unset_userdata('breadcrumbs');
    $ci->session->set_userdata('breadcrumbs', array());
}

/**
 * Function to add breadcrumbs to session
 * @access public
 * @param  string $key
 * @param  string $url
 */
function store_breadcrumbs($key, $url = NULL)
{
    $ci = &get_instance();
    
    $breadcrumbs = $ci->session->userdata('breadcrumbs');
    if( isset($breadcrumbs[$key]) )
    {
        $breadcrumbs = array_slice($breadcrumbs, 0, array_search($key, array_keys($breadcrumbs)));
    }
    $breadcrumbs[$key] = $url ? $url : NULL;
    $ci->session->set_userdata('breadcrumbs', $breadcrumbs);
}

/**
 * Function to build breadcrumbs from session
 * @access public
 */
function build_breadcrumbs()
{
    $ci = &get_instance();
    
    $ci->breadcrumb->clear();
    $breadcrumbs = $ci->session->userdata('breadcrumbs');
    foreach ($breadcrumbs as $key => $url)
    {
        end($breadcrumbs);
        if ($key === key($breadcrumbs))
        {
            $ci->breadcrumb->add_crumb($key);
        } else
        {
            $url = $url ? base_url() . $url : NULL;
            $ci->breadcrumb->add_crumb($key, $url);
        }
    }
}

/**
 * Convert ascii and special characters to html equivalent
 * @access public
 * @param string $string String to be cleaned
 * @return string returns Html encoded string
 */
function clean_text($string)
{
    $ci = &get_instance();
    $ci->load->helper('string');
    
    $clean = htmlentities( ascii_to_entities($string), ENT_QUOTES, 'utf-8', FALSE);
    return $clean;
}

/*
* Method for validating content id.
* @access public
* @retrun bool Returns true if the validation was successful, otherwise false.
*/
function valid_id()
{
   $ci = &get_instance();
   $ci->form_validation->set_rules('id', 'ID', 'trim|required|numeric|xss_clean');
   if ($ci->form_validation->run() == FALSE)
   {
       return false;
   } else
   {
       return true;
   }
}

/*
* Method for validating get id.
* @access public
* @retrun bool Returns true if the validation was successful, otherwise false.
*/
function valid_get_id($id)
{
   $ci = &get_instance();
   $validator = $ci->form_validation;
   
   $valid_id        = TRUE;
   $valid_number    = $valid_id && $validator->numeric($id);
   $valid_xss       = $valid_number && $validator->xss_clean($id);
   $valid_length    = $valid_xss && $validator->max_length($id, 10);
   
   return $valid_length;
}

/**
 * Function for uploading images
 * @param string $name Name of the file input field
 * @param string $path Location of the directory from which the image will be uploaded
 * @param string $action Switch string between add or edit
 * @param string $file_type Pipe separated string of valid image file types
 * @param int $width New image width
 * @param int $height New image height
 * @param string $image The name of the image being edited, use only when editing
 * @return boolean/string Returns the filename of the image uploaded, otherwise false
 */
function valid_image_upload($name, $path, $action = 'add', $file_type = 'gif|jpg|png', $width = 1024, $height = 768, $image = 'tmp.jpg')
{
    $ci = &get_instance();
    
    $config['upload_path']          = './' . $path;
    $config['allowed_types']        = $file_type;
    $config['max_size']             = '0'; // any size, let php ini decide
    $config['max_width']            = '0'; // any width
    $config['max_height']           = '0'; // any height
    $ci->load->library('upload', $config);
    
    $ci->upload->initialize($config);
    
    if ( $ci->upload->do_upload($name) )
    {
        $upload_data = $ci->upload->data();
        $image_name = $upload_data['file_name'];

        // image size configuration
        $img_config['image_library']        = 'gd2';
        $img_config['source_image']         = FCPATH . $path . $image_name;
        $img_config['maintain_ratio']       = TRUE;
        $img_config['width']                = $width;
        $img_config['height']               = $height;

        // resize image
        $ci->load->library('image_lib', $img_config);
        $ci->image_lib->resize();
        
        if($action === 'edit')
        {
            // remove the old image from directory
            if (TRUE === file_exists(FCPATH . $path . $image))
            {
                unlink(FCPATH . $path . $image);
            }
        }

        return $image_name;
        
    } else
    {
        $ci->form_validation->set_errors( array($name . '_image' => $ci->upload->display_errors()) );
        return FALSE;
    }
}


/**
 * Generate Link Headers for sortable Tables.
 * @acces public
 * @param array $headers Array containing all table headers.
 * @param string $what String containing the name of the data.
 * @param int $controls Number of controls for each data.
 * @return string Returns markup for sortable html table headers.
 */
function create_datatable_headers($headers, $what, $controls = 2, $options = TRUE)
{
    $thead = '<tr class="thefilter script_show">';
    if($options)
    {
        $thead .= '<th class="with-checkbox"></th>';
    }
    
    $counter = 0;
    foreach ($headers as $key => $value)
    {
        if($counter === 0 OR $counter === count($headers) - 1)
        {
            $thead .= '<th>' .$value. '</th>';
        } else
        {
            $thead .= '<th class="hidden-480">' .$value. '</th>';
        }
        $counter++;
    }
    
    if($options)
    {
        $thead .= '<th width="' .(int)$controls * 35 . '">Options</th>';
    }
                
    $thead .= '</tr><tr>';
            
    if($options)
    {
        $thead .= '<th class="with-checkbox"><input type="checkbox" name="check_all" id="check_all" class="script_show"></th>';
    }
    
    $counter = 0;
    foreach ($headers as $key => $value)
    {
        if($counter === 0 OR $counter === count($headers) - 1)
        {
            $thead .= '<th>' .$value. '</th>';
        } else
        {
            $thead .= '<th class="hidden-480">' .$value. '</th>';
        }
        $counter++;
    }
    
    if($options)
    {
        $thead .= '<th width="' .(int)$controls * 35 . '">Options</th>';
    }
    
    $thead .= '</tr>';
    
    return $thead;
}


/**
 * Function to convert time on desired time format
 * @access public
 * @param string $time
 * @return date Returns formatted time
 */
function cms_time($time)
{
    $time = date('h:i:s A', strtotime($time));
    return $time;
}

/**
 * Function to convert date on desired format
 * @access public
 * @param string $date_time
 * @return date Returns formatted date
 */
function cms_date($date)
{
    $date = date('M d, Y', strtotime($date));
    return $date;
}

/**
 * Function to convert date on desired format
 * @access public
 * @param string $date_time
 * @return date Returns formatted date and time
 */
function cms_datetime($date_time)
{
    $date = date('M d, Y h:i A', strtotime($date_time));
    return $date;
}

/**
 * Function to convert url to links
 * @access public
 * @param string $url
 * @return date Returns url link
 */
function cms_url($url)
{
    $url = "<a href=\"{$url}\" >{$url}</a>";
    return $url;
}

/**
 * Function to convert email to links
 * @access public
 * @param string $url
 * @return date Returns email link
 */
function cms_email($email)
{
    $email = "<a href=\"mailto:{$email}\" >{$email}</a>";
    return $email;
}

/* End of file cms_helper.php */
/* Location: ./application/helpers/cms_helper.php */